package com.gofaraway.start.exception;

import com.gofaraway.common.domin.Response;
import com.gofaraway.common.exception.STORuntimeException;
import com.gofaraway.common.exception.Error;
import com.gofaraway.common.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

import static com.gofaraway.common.exception.BusinessException.BUSINESS_ERROR_CODE_PREFIX;
import static com.gofaraway.common.exception.BusinessException.EXCEPTION_ERROR_CODE_A0102;

/**
 * Controller 全局异常捕获
 *
 * @author ChenPeng
 * @Date 2024/5/17 9:19
 */
//@ControllerAdvice
@Slf4j
@Deprecated
public class GlobalControllerException {

    //@ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handleDefaultException(Exception exception) {
        log.error("controller层统一异常：", exception);
        //主动抛出的异常
        //1 异常日志记录,便于排查和风险问题解除
        if (exception instanceof STORuntimeException) {
            Error error = ((STORuntimeException) exception).getError();
            // 业务异常，主动抛给用户，系统无需人工干预处理
            if (error.getCode().contains(BUSINESS_ERROR_CODE_PREFIX)) {
                return Response.error(error.getCode(), error.getMessage());
            }
        }
        //2 参数非空统一校验
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException violationException = (ConstraintViolationException) exception;
            String newMessage = violationException.getMessage().replaceAll("businessExceptionFromValid.arg0.", "");
            Error error = EXCEPTION_ERROR_CODE_A0102.withMessage(newMessage);
            // 业务异常，主动抛给用户，系统无需人工干预处理
            return Response.error(error.getCode(), error.getMessage());
        }
        //系统异常，给用户的提示统一包装，不通过前端返回进行异常信息包裹
        return Response.error(SystemException.EXCEPTION_ERROR_CODE_B0001.getCode(), SystemException.EXCEPTION_ERROR_CODE_B0001.getMessage());
    }

}
